package com.metersbonwe.basetest.proxy;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;

/**
 * 代理工具类
 * 
 * @author 张瑞雨
 * 
 */
public class Proxys {

	/**
	 * 
	 * @param klass
	 * @param callback
	 * @return
	 */
	public static Object getProxyInstance(Class<?> klass, Callback callback) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(klass);
		enhancer.setCallback(callback);
		return enhancer.create();
	}

	public static Method getMethodByAnnotationClass(Object obj, Class<? extends Annotation> annotationClass) {
		Method[] methods = obj.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			Method md = methods[i];
			if (md.getAnnotation(annotationClass) != null) {
				return md;
			}
		}
		return null;
	}

	public static Field getFieldByAnnotationClass(Object obj, Class<? extends Annotation> annotationClass) {
		Field[] field = obj.getClass().getDeclaredFields();
		for (int j = 0; j < field.length; j++) {
			if (null != field[j].getAnnotation(annotationClass)) {
				return field[j];
			}
		}
		return null;
	}

	public static Object execMethod(Object obj, Method method, Object... args) throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		return method.invoke(obj, args);
	}

	public static boolean containsAnnotation(Object obj, Class<? extends Annotation> klass) {
		return obj.getClass().getAnnotation(klass) == null;
	}

	public static void setFieldValueByAnnotation(Object source, int i, Class<? extends Annotation> klass) throws IllegalArgumentException, IllegalAccessException {
		Field field = getFieldByAnnotationClass(source, klass);
		if(field == null) return;
		boolean flag = field.isAccessible();
		field.setAccessible(true);
		field.set(source, i);
		field.setAccessible(flag);
	}
}
